package com.study.scapp.info.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.study.scapp.info.common.CommonResult;
import com.study.scapp.info.pojo.InfoCategory;
import com.study.scapp.info.pojo.InfoCommodity;
import com.study.scapp.info.service.InfoCategoryService;
import com.study.scapp.info.service.InfoCommodityService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * @author 1
 * @data 2023/5/14
 * 商品分类
 */
@RestController
@RequestMapping("/category")
public class InfoCategoryController {

    @Resource
    private InfoCategoryService infoCategoryService;

    @Resource
    private InfoCommodityService infoCommodityService;


    /**
     * 新增分类
     * @param category
     * @return
     */
    @PostMapping("/add")
    public CommonResult addCategory(@RequestParam Map<String, Object> category){
        JSONObject jsonObject = new JSONObject();
        jsonObject.putAll(category);
        InfoCategory infoCategory = jsonObject.toJavaObject(InfoCategory.class);
        QueryWrapper<InfoCategory> infoCategoryQueryWrapper = new QueryWrapper<>();
        infoCategoryQueryWrapper.eq("category_name",infoCategory.getCategoryName());
        List<InfoCategory> list = infoCategoryService.list(infoCategoryQueryWrapper);
        if (list.size()>=1){
            return CommonResult.failed("该分类已存在！");
        }
        infoCategoryService.save(infoCategory);
        return CommonResult.success("新增成功！");
    }

    /**
     * 分类列表接口
     * @return
     */
    @GetMapping("/list")
    public CommonResult listCategories(){
        List<InfoCategory> list = infoCategoryService.list(new QueryWrapper<InfoCategory>().orderByDesc("create_time"));
        return CommonResult.success(list);
    }

    /**
     * 分类删除接口
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public CommonResult deleteCategory(@PathVariable("id") Long id){
        boolean b = infoCategoryService.removeById(id);
        if (b){
            return CommonResult.success("删除分类成功！");
        }else {
            return CommonResult.failed("删除失败！");
        }
    }

    /**
     * 根据分了i获取
     * @param name
     * @return
     */
    @GetMapping("/listByCategory")
    public CommonResult listByCategory(String name){
        QueryWrapper<InfoCommodity> commodityQueryWrapper = new QueryWrapper<>();
        commodityQueryWrapper.eq("category",name);
        return CommonResult.success(infoCommodityService.list(commodityQueryWrapper));

    }

}
